import requests
import json
import os
from lxml import etree


def skin_request():
    page = requests.get(url=json_url, headers=headers).text
    html = json.loads(page)
    hero_list = []
    for hero in html:
        hero_one = {}
        hero_one['name'] = hero['cname']
        hero_one['ename'] = hero['ename']
        hero_list.append(hero_one)
    skin_get(hero_list)


def skin_get(hero_list):
    for i in hero_list:
        ename = str(i['ename'])
        for j in range(1, 10):
            skin_url = 'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/' + ename + '/' + ename + '-bigskin-' + str(j) + '.jpg'
            print(skin_url)

            skin = requests.get(url=skin_url, headers=headers)

            if skin.status_code == 200:
                path = save(i['name'])
                skin_name = i['name'] + str(j) + '.jpg'
                with open(path + '/' + skin_name, 'wb') as f:
                    f.write(skin.content)
            else:
                break




        # detail_url = 'https://pvp.qq.com/web201605/herodetail/' + str(ename) + '.shtml'
        # hero_page = etree.HTML(requests.get(url=detail_url, headers=headers).content.decode('GBK'))
        # # 皮肤列表
        # hero_detail = hero_page.xpath('//ul[@class="pic-pf-list pic-pf-list3"]')
        # print(hero_detail)
        # skin_href = hero_detail.xpath('./li/i/img/@data-imgname')
        # skin_list = hero_detail.xpath('./li/p/text()')
        # print(skin_href)


def save(name):
    path1 = os.path.dirname(__file__) + '/皮肤'
    os.chdir(path1)
    path = path1 + '/' + name
    if not os.path.exists(path):
        os.mkdir(name)
    return path

if __name__ == '__main__':
    main_url = 'https://pvp.qq.com/web201605/herolist.shtml'
    json_url = 'https://pvp.qq.com/web201605/js/herolist.json'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36',
    }
    # save('a')
    skin_request()






